﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace WPS.Modules.StyleLibrary
{
	/// <summary>
	/// Page to return wysiwyg.css file with disabling cache.
	/// WYSIWYG and Style Library previews use this css loading.
	/// </summary>
	public partial class IncludeCssNoCache : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			// Authenticate user
			IStyleLibraryIntegration cms = new StyleLibraryIntegration();
			if(!cms.CheckAccess())
			{
				Response.Redirect(cms.GetLoginPage(), true);
			}

			// WYSIWYG and Style Library previews use this css loading.
			string fName = Server.MapPath(cms.GetEditableCssWebPath());

			if(File.Exists(fName))
			{
				DumpFile(fName, "text/css");
			}
			else
			{
				// Css not found - return empty file to make DOM OK on client side
				Response.ContentType = "text/css";
				Response.End();
			}
		}


		/// <summary>
		/// Dumps a binary or text file to the response stream and ends response.
		/// </summary>
		/// <param name="path">Full path to the file to load and send.</param>
		/// <param name="contentType">Mime type of the file.</param>
		private void DumpFile(string path, string contentType)
		{
			HttpContext.Current.Response.ContentType = contentType; //"application/x-zip-compressed"
			HttpContext.Current.Response.Expires = -1;

			FileInfo file = new FileInfo(path);
			HttpContext.Current.Response.AppendHeader("Content-Disposition", "inline; filename=\"" + file.Name + "\"");
			HttpContext.Current.Response.Write(File.ReadAllText(path));
			HttpContext.Current.Response.End();
		}

	}
}